<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"inkgn.gitee.io","root":"/","scheme":"Muse","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta name="description" content="温故知新Math.ceil();  &#x2F;&#x2F;向上取整。">
<meta property="og:type" content="article">
<meta property="og:title" content="js生成[n,m]的随机数">
<meta property="og:url" content="https://inkgn.gitee.io/2020/09/08/article18/index.html">
<meta property="og:site_name" content="静水深流">
<meta property="og:description" content="温故知新Math.ceil();  &#x2F;&#x2F;向上取整。">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2020-09-08T09:56:13.000Z">
<meta property="article:modified_time" content="2020-09-08T09:56:13.000Z">
<meta property="article:author" content="yinks">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://inkgn.gitee.io/2020/09/08/article18/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>js生成[n,m]的随机数 | 静水深流</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">静水深流</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/categories" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
        <li class="menu-item menu-item-motto">

    <a href="/motto/motto" rel="section"><i class="fa fa-book fa-fw"></i>古训</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/me" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://inkgn.gitee.io/2020/09/08/article18/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="https://blog-1253246719.cos.ap-chengdu.myqcloud.com/blog/user_info/face">
      <meta itemprop="name" content="yinks">
      <meta itemprop="description" content="长路漫漫，半程风雨，半程春">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="静水深流">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          js生成[n,m]的随机数
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2020-09-08 17:56:13" itemprop="dateCreated datePublished" datetime="2020-09-08T17:56:13+08:00">2020-09-08</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/js/" itemprop="url" rel="index"><span itemprop="name">js</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h2 id="温故知新"><a href="#温故知新" class="headerlink" title="温故知新"></a>温故知新</h2><p>Math.ceil();  //向上取整。</p>
<p>Math.floor();  //向下取整。</p>
<p>Math.round();  //四舍五入。</p>
<p>Math.random();  //0.0 ~ 1.0 之间的一个伪随机数。【包含0不包含1】 //比如0.8647578968666494</p>
<p>Math.ceil(Math.random()*10);      // 获取从1到10的随机整数 ，取0的概率极小。</p>
<p>Math.round(Math.random());   //可均衡获取0到1的随机整数。</p>
<p>Math.floor(Math.random()*10);  //可均衡获取0到9的随机整数。</p>
<p>Math.round(Math.random()*10);  //基本均衡获取0到10的随机整数，其中获取最小值0和最大值10的几率少一半。</p>
<p>因为结果在0~0.4 为0，0.5到1.4为1…8.5到9.4为9，9.5到9.9为10。所以头尾的分布区间只有其他数字的一半。</p>
<h2 id="生成-n-m-的随机整数"><a href="#生成-n-m-的随机整数" class="headerlink" title="生成[n,m]的随机整数"></a>生成[n,m]的随机整数</h2><p>函数功能：生成[n,m]的随机整数。</p>
<p>在js生成验证码或者随机选中一个选项时很有用</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">//生成从minNum到maxNum的随机数</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">randomNum</span>(<span class="params">minNum,maxNum</span>)</span>&#123; </span><br><span class="line">    <span class="keyword">switch</span>(<span class="built_in">arguments</span>.length)&#123; </span><br><span class="line">        <span class="keyword">case</span> <span class="number">1</span>: </span><br><span class="line">            <span class="keyword">return</span> <span class="built_in">parseInt</span>(<span class="built_in">Math</span>.random()*minNum+<span class="number">1</span>,<span class="number">10</span>); </span><br><span class="line">        <span class="keyword">break</span>; </span><br><span class="line">        <span class="keyword">case</span> <span class="number">2</span>: </span><br><span class="line">            <span class="keyword">return</span> <span class="built_in">parseInt</span>(<span class="built_in">Math</span>.random()*(maxNum-minNum+<span class="number">1</span>)+minNum,<span class="number">10</span>); </span><br><span class="line">        <span class="keyword">break</span>; </span><br><span class="line">            <span class="keyword">default</span>: </span><br><span class="line">                <span class="keyword">return</span> <span class="number">0</span>; </span><br><span class="line">            <span class="keyword">break</span>; </span><br><span class="line">    &#125; </span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h2 id="分析"><a href="#分析" class="headerlink" title="分析"></a>分析</h2><p>Math.random()生成[0,1)的数，所以</p>
<p>Math.random()*5生成{0,5)的数。</p>
<p>通常期望得到整数，所以要对得到的结果处理一下。</p>
<p>parseInt()，Math.floor()，Math.ceil()和Math.round()都可得到整数。</p>
<p>parseInt()和Math.floor()结果都是向下取整。</p>
<p>所以Math.random()*5生成的都是[0,4] 的随机整数。</p>
<h3 id="所以生成-1-max-的随机数，公式如下："><a href="#所以生成-1-max-的随机数，公式如下：" class="headerlink" title="所以生成[1,max]的随机数，公式如下："></a>所以生成[1,max]的随机数，公式如下：</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// max - 期望的最大值</span></span><br><span class="line"><span class="built_in">parseInt</span>(<span class="built_in">Math</span>.random()*max,<span class="number">10</span>)+<span class="number">1</span>;</span><br><span class="line"><span class="built_in">Math</span>.floor(<span class="built_in">Math</span>.random()*max)+<span class="number">1</span>;</span><br><span class="line"><span class="built_in">Math</span>.ceil(<span class="built_in">Math</span>.random()*max);</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="所以生成-0-max-到任意数的随机数，公式如下："><a href="#所以生成-0-max-到任意数的随机数，公式如下：" class="headerlink" title="所以生成[0,max]到任意数的随机数，公式如下："></a>所以生成[0,max]到任意数的随机数，公式如下：</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// max - 期望的最大值</span></span><br><span class="line"><span class="built_in">parseInt</span>(<span class="built_in">Math</span>.random()*(max+<span class="number">1</span>),<span class="number">10</span>);</span><br><span class="line"><span class="built_in">Math</span>.floor(<span class="built_in">Math</span>.random()*(max+<span class="number">1</span>));</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="所以希望生成-min-max-的随机数，公式如下："><a href="#所以希望生成-min-max-的随机数，公式如下：" class="headerlink" title="所以希望生成[min,max]的随机数，公式如下："></a>所以希望生成[min,max]的随机数，公式如下：</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// max - 期望的最大值</span></span><br><span class="line"><span class="comment">// min - 期望的最小值</span></span><br><span class="line"><span class="built_in">parseInt</span>(<span class="built_in">Math</span>.random()*(max-min+<span class="number">1</span>)+min,<span class="number">10</span>);</span><br><span class="line"><span class="built_in">Math</span>.floor(<span class="built_in">Math</span>.random()*(max-min+<span class="number">1</span>)+min);</span><br><span class="line"></span><br></pre></td></tr></table></figure>
    </div>

    
    
    
        

<div>
<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>yinks
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://inkgn.gitee.io/2020/09/08/article18/" title="js生成[n,m]的随机数">https://inkgn.gitee.io/2020/09/08/article18/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>


      <footer class="post-footer">

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2020/02/19/list5/" rel="prev" title="播放器 2.0 版本更新 完美适配移动端">
      <i class="fa fa-chevron-left"></i> 播放器 2.0 版本更新 完美适配移动端
    </a></div>
      <div class="post-nav-item">
    <a href="/2020/11/23/vue-pro3/" rel="next" title="vue项目练习笔记">
      vue项目练习笔记 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%B8%A9%E6%95%85%E7%9F%A5%E6%96%B0"><span class="nav-number">1.</span> <span class="nav-text">温故知新</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%94%9F%E6%88%90-n-m-%E7%9A%84%E9%9A%8F%E6%9C%BA%E6%95%B4%E6%95%B0"><span class="nav-number">2.</span> <span class="nav-text">生成[n,m]的随机整数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%88%86%E6%9E%90"><span class="nav-number">3.</span> <span class="nav-text">分析</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%89%80%E4%BB%A5%E7%94%9F%E6%88%90-1-max-%E7%9A%84%E9%9A%8F%E6%9C%BA%E6%95%B0%EF%BC%8C%E5%85%AC%E5%BC%8F%E5%A6%82%E4%B8%8B%EF%BC%9A"><span class="nav-number">3.1.</span> <span class="nav-text">所以生成[1,max]的随机数，公式如下：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%89%80%E4%BB%A5%E7%94%9F%E6%88%90-0-max-%E5%88%B0%E4%BB%BB%E6%84%8F%E6%95%B0%E7%9A%84%E9%9A%8F%E6%9C%BA%E6%95%B0%EF%BC%8C%E5%85%AC%E5%BC%8F%E5%A6%82%E4%B8%8B%EF%BC%9A"><span class="nav-number">3.2.</span> <span class="nav-text">所以生成[0,max]到任意数的随机数，公式如下：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%89%80%E4%BB%A5%E5%B8%8C%E6%9C%9B%E7%94%9F%E6%88%90-min-max-%E7%9A%84%E9%9A%8F%E6%9C%BA%E6%95%B0%EF%BC%8C%E5%85%AC%E5%BC%8F%E5%A6%82%E4%B8%8B%EF%BC%9A"><span class="nav-number">3.3.</span> <span class="nav-text">所以希望生成[min,max]的随机数，公式如下：</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="yinks"
      src="https://blog-1253246719.cos.ap-chengdu.myqcloud.com/blog/user_info/face">
  <p class="site-author-name" itemprop="name">yinks</p>
  <div class="site-description" itemprop="description">长路漫漫，半程风雨，半程春</div>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://gitee.com/inkgn" title="Gitee → https:&#x2F;&#x2F;gitee.com&#x2F;inkgn" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>Gitee</a>
      </span>
      <span class="links-of-author-item">
        <a href="/2087104694@qq.com" title="E-Mail → 2087104694@qq.com"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">yinks</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://muse.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/muse.js"></script>


<script src="/js/next-boot.js"></script>




  















  

  

</body>
</html>
